<?php
namespace app\common\model;
use think\Model;
use think\DB;
use think\Cache;
class User extends Model{
	// 定义时间戳字段名
	protected $createTime = '';
	protected $updateTime = '';	
	// 自动完成
	protected $insert = ['user_admin'=>0,'user_reg_time','user_last_login_time','user_reg_ip','user_last_login_ip','user_status'=>1,'user_nickname'];	//新增
	protected $update = ['user_last_login_ip','user_last_login_time'];	//更新
	protected function setUserRegTimeAttr($value){
		return time();
	}
	protected function setUserLastLoginTimeAttr($value){
		return time();
	}		
    protected function setUserNicknameAttr($value,$data){
		if($value){
			return $value;
		}else{
			return $data['user_name'];
		}
    }	
    protected function setUserRegIpAttr(){
        return bindec(decbin(ip2long(request()->ip())));
    }
	protected function setUserLastLoginIpAttr(){
		return bindec(decbin(ip2long(request()->ip())));
	}	
	protected function setUserPasswordAttr($value,$data){
		return md5(md5($value).$data['user_salt']);
	}
	public function login($username = '', $password = '', $type = 1){
		if(empty($username) || empty($password)){
			$this->error = '用户名或密码为空';
			return false;
		}
		$map = array();
		if (\think\Validate::is($username,'email')) {
			$type = 2;
		} elseif (preg_match("/^1[34578]{1}\d{9}$/",$username)){
			$type = 3;
		}
		switch ($type) {
			case 1:
				$map['user_name'] = $username;
				break;
			case 2:
				$map['user_email'] = $username;
				break;
			case 3:
				$map['user_mobile'] = $username;
				break;
			case 4:
				$map['user_id'] = $username;
				break;
			default:
				$this->error = '参数错误';
			    return false;
		}
		if(empty($map)){
			$this->error = '参数错误';
			return false;			
		}
		$user = $this->where($map)->find();
		if($user['user_id']){
		    if($user['user_status']==0){
			    $this->error = '用户已锁定';
			    return false;
		    }			
			if(md5(md5($password).$user['user_salt']) === $user['user_password']) {
				$this->autoLogin($user); //更新用户登录信息
				return $user; //登录成功，返回用户信息
			}else{
			    $this->error = '密码错误';
			    return false;
		    }				
		}else{
			$this->error = '用户不存在';
			return false;
		}
	}
	//修改用户资料
	public function editUser($data, $ischangepwd = false){
		if ($data['user_id']) {
			if (!$ischangepwd || ($ischangepwd && $data['user_password'] == '')) {
				unset($data['user_salt']);
				unset($data['user_password']);
			}else{
				$data['user_salt'] = rand_string(6);
			}
			if($this->validate('user.edit')->save($data, array('user_id'=>$data['user_id'],'user_admin'=>0))!== false){
			}else{
				$this->error = $this->getError();
				return false;
			}
		}else{
			$this->error = "非法操作！";
			return false;
		}
	}
	
	public function editpw($data, $is_reset = false){
		$uid = $is_reset ? $data['uid'] : session('member_auth.uid');
		if (!$is_reset) {
			//后台修改用户时可修改用户密码时设置为true
			$checkPassword=$this->checkPassword($uid,$data['oldpassword']);
			$validate = $this->validate('member.password');
			if (false === $validate || false === $checkPassword) {
				return false;
			}
		}
		$data['salt'] = rand_string(6);
		return $this->save($data, array('uid'=>$uid));
	}

	protected function checkPassword($uid,$password){
		if (!$uid && !$password) {
			$this->error = '原始用户UID和原密码不能为空';
			return false;
		}
		$user = $this->where(array('uid'=>$uid))->find();
		if (md5(md5($password).$user['salt']) === $user['password']) {
			return true;
		}else{
			$this->error = '原始密码错误！';
			return false;
		}
	}	
	function reg($array=[],$isautologin=true){
		$data=[];
		$user_api=cookie('user_auth_api');
		$data['user_name']=htmlspecialchars(urldecode(trim($array['user_name'])));
		$data['user_nickname']=htmlspecialchars(urldecode(trim($array['user_nickname'])));
		$data['user_password']=htmlspecialchars(urldecode(trim($array['user_password'])));
		$data['user_mobile']=(string)$array['user_mobile'];
		$data['user_email']=(string)$array['user_email'];
		$data['user_uid']=intval($array['user_uid']);
		if($GLOBALS['config']['user']['sys']['user_reg_email']){
		    $data['user_isemail']=2;
		}
		if($GLOBALS['config']['user']['sys']['user_reg_sms']){
			$data['user_ismobile']=1;
		}else{
			$data['user_isemail']=0;
		}		
		//是否存在第三方登录信息
		if($user_api['openid']){
		    $data['user_nickname']=(string)htmlspecialchars(urldecode(trim($user_api['nickname'])));	
		    $channel=htmlspecialchars(urldecode(trim($user_api['channel'])));
		    $data[$channel.'_openid']=(string)htmlspecialchars(urldecode(trim($user_api['openid'])));
		    $data[$channel.'_pic']=$user_api['avatar'];
		    $data['user_sex']=htmlspecialchars(urldecode(trim($user_api['sex'])));
		    $data['user_prov']=htmlspecialchars(urldecode(trim($user_api['province'])));
		    $data['user_city']=htmlspecialchars(urldecode(trim($user_api['city'])));
		    $data['user_isemail']=0;
			$data['user_ismobile']=0;
		}
        $data['user_groupid']=$GLOBALS['config']['user']['sys']['user_reg_default_group'];		
		$data['user_salt'] = rand_string(6);
		if($this->validate('user.add')->allowField(true)->save($data)!== false){
			if($isautologin){
				$this->autoLogin($this->data);
			}
			$data['group_id']=$GLOBALS['config']['user']['sys']['user_reg_default_group'];
			if($GLOBALS['config']['user']['sys']['user_reg_score']){
				model('Score')->user_score($this->user_id,1,intval($GLOBALS['config']['user']['sys']['user_reg_score']));  
			}
			if($GLOBALS['config']['user']['sys']['user_reg_vip']){
				$data['group_id']=$GLOBALS['config']['user']['sys']['user_reg_vip_group'];
				model('Score')->user_reg_time($this->user_id,intval($GLOBALS['config']['user']['sys']['user_reg_vip']));  
			}				   
			if($this->user_uid && $GLOBALS['config']['user']['sys']['user_reg_score_uid']){
				model('Score')->user_score($this->user_uid,9,intval($GLOBALS['config']['user']['sys']['user_reg_score_uid'])); 
			}		
			return $this;
		}else{
			if(!$this->getError()){
				$this->error = $this->getError();
			}
			return false;
		}
	}	
	/**
	 * 自动登录用户
	 * @param  integer $user 用户信息数组
	 */
	private function autoLogin($user){
		/* 更新登录信息 */
		$data = array(
			'user_id'         => $user['user_id'],
			'user_login'           => Db::raw('user_login+1'),
			'user_last_login_time' => time(),
			'user_last_login_ip'   => bindec(decbin(ip2long(request()->ip()))),
		);
		$this->allowField(true)->save($data,['user_id' =>$user['user_id']]);
		$user = $this->find($user['user_id']);
		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'user_id'             => $user['user_id'],
			'user_name'        => $user['user_name'],
			'user_nickname'        => !$user['user_nickname'] ? $user['user_nickname'] : $user['user_name'],
			'user_email'        => $user['user_email'],
			'user_isemail'  => $user['user_isemail'],
			'user_last_login_time' => $user['user_last_login_time'],
		);
		cookie('user_auth_api',NULL);
		if(!empty($user['user_email']) && $GLOBALS['config']['user']['sys']['user_reg_email']==1 && $user['user_isemail']==2){
			cookie('user_auth_temp',$auth,3600);
		    cookie('user_auth',NULL);
		    cookie('user_auth_sign',NULL);	
		    session('user_auth',NULL);
		    session('user_auth_sign',NULL);			
		}else{
            cookie('user_auth_temp',NULL);			
		    cookie('user_auth',$auth);
		    cookie('user_auth_sign',data_auth_sign($auth));	
		    session('user_auth',$auth);
		    session('user_auth_sign',data_auth_sign($auth));
		}				
	}
	/**
	 * 自动登录用户
	 * @param  integer $user 用户信息数组
	 */
	public function createAccessToken($user){
		/* 更新登录信息 */
		$data = array(
			'user_id'         => $user['user_id'],
			'user_login'           => Db::raw('user_login+1'),
			'user_last_login_time' => time(),
			'user_last_login_ip'   => bindec(decbin(ip2long(request()->ip()))),
		);
		$this->allowField(true)->save($data,['user_id' =>$user['user_id']]);
		$user = $this->find($user['user_id']);
		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'user_id'             => $user['user_id'],
			'user_name'        => $user['user_name'],
			'user_nickname'        => !$user['user_nickname'] ? $user['user_nickname'] : $user['user_name'],
			'user_email'        => $user['user_email'],
			'user_isemail'  => $user['user_isemail'],
			'user_last_login_time' => $user['user_last_login_time'],
		);
		return data_auth_sign($auth);
	}
	public function signout(){
		cookie('user_auth_api',NULL);
		cookie('user_auth_temp',NULL);
		cookie('user_auth',NULL);
		cookie('user_auth_sign',NULL);	
		session('user_auth',NULL);
		session('user_auth_sign',NULL);	
	}	
	public function getInfo($id){
		$data = $this->where(array('user_id'=>$id))->find();
		if(!empty($data)){
			return $data;
		}else{
			return false;
		}
	}
	//获取用户资料
	public function get_user_info($user_id){
		if($user_id){
		    $user = $this->join('auth_group group','group.id=user_groupid','LEFT')->find($user_id);
		    if($user){
			    return $user;
		    }else{
		        return false;
		    }
		}else{
		    return false;
		}	
	}
	/**
	 * 第三方绑定查询
	*/
	public function GetApiUser($openid='',$channel='qq'){
		$where[$channel.'_openid']=$openid;
		$user=db('user')->where($where)->find();
		if($user['user_id']){
		    if($user['user_status']!=1){
				$this->error('用户被禁用');
		    }
		    $this->autoLogin($user);//更新登录信息
		    return $user;	
		}else{
		    return false;		
		}
	}
	public function access(){
        // 用户HAS ONE档案关联
        return $this->hasOne('AuthGroupAccess','uid');
    }
	public function extend(){
		return $this->hasOne('MemberExtend', 'uid');
	}
	public function visitors(){
        return $this->hasMany('visitors','visitors_userid','','','LEFT');
    }	
	public function comment(){
        return $this->hasMany('cm','cm_uid','','','LEFT');
    }
	public function favorite(){
        return $this->hasMany('Favorite','favorite_uid','','','LEFT');
    }	
	public function remind(){
        return $this->hasMany('Remind','remind_uid','','','LEFT');
    }	
	public function playlog(){
        return $this->hasMany('Playlog','log_uid','','','LEFT');
    }
	public function gb(){
        return $this->hasMany('gb','gb_uid','','','LEFT');
    }
	public function order(){
        return $this->hasMany('orders','order_uid','','','LEFT');
    }	
	public function msg(){
        return $this->hasMany('msg','msg_uid','','','LEFT');
    }
	public function score(){
        return $this->hasMany('score','score_uid','','','LEFT');
    }
	public function role(){
        return $this->hasMany('role','role_uid','','','LEFT');
    }
	public function part(){
        return $this->hasMany('part','part_uid','','','LEFT');
    }
	public function theme(){
        return $this->hasMany('theme','theme_uid','','','LEFT');
    }
	public function lines(){
        return $this->hasMany('lines','lines_uid','','','LEFT');
    }
	public function music(){
        return $this->hasMany('music','music_uid','','','LEFT');
    }	
    public function up_group($uid=''){
		if($uid){
			$where=[];
			$where['user_id']=$uid;
			$where['user_admin']=0;
            $info=$this->where($where)->find();	
            if($info['user_id']){			
			    if($info['user_viptime']>time()){
				    $group_id=$GLOBALS['config']['user']['sys']['user_reg_vip_group'];
			    }else{
				    $group_id=$GLOBALS['config']['user']['sys']['user_reg_default_group'];
			    }
				db('user')->where($where)->setField('user_groupid',$group_id);
            }				
		}
    }		
	//事件注册
    protected static function init(){
		//写入后置事件
		User::afterWrite(function($user){
			if(isset($user->user_id)){
			    model('user')->up_group($user->user_id);
			}
		});		
		//删除后置事件
        User::afterDelete(function($user){
			//删除关联数据
			db('auth_group_access')->where('uid',$user->user_id)->delete();
		    db('msg')->where('msg_uid',$user->user_id)->delete();
			db('favorite')->where('favorite_uid',$user->user_id)->delete();
			db('remind')->where('remind_uid',$user->user_id)->delete();
			db('gb')->where('gb_uid',$user->user_id)->delete();
			db('cm')->where('cm_uid',$user->user_id)->delete();
			db('playlog')->where('log_uid',$user->user_id)->delete();
			db('score')->where('score_uid',$user->user_id)->delete();
			db('orders')->where('order_uid',$user->user_id)->delete();
       });	
    }

    //数据查询	
    public function listData($tag){
		$param = zanpiancms_param_url();
		if(!is_array($tag)) {
            $tag=json_decode($tag, true);
        }
		$tag['field']= !empty($tag['field']) ? $tag['field'] : '*';
		$tag['limit']= !empty($tag['limit']) ? $tag['limit'] : 10;
		if(!empty($tag['page']) && !empty($param['order'])){
			$tag['order']='user_'.$param['order'].' desc';
		}		
		if(empty($tag['order'])){
			$tag['order']='user_last_login_time desc';
		}
		$cahce=tag_cache($tag);
	    //优先从缓存调用数据及分页变量
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){			
			$data_cache_content = Cache::get($cahce['cache_name']);
			if($data_cache_content){
				return $data_cache_content;
			}
		}		
		$where=[];
		$where['user_status']=['eq',1];
        $where['user_admin']=['eq',0];			
	    if(!empty($tag['ids'])) {
		    $ids = explode(',',$tag['ids']);
		    if(count($ids)>1) {
			    $where['user_id'] = array('in',$tag['ids']);
		    }else{
			    $where['user_id'] = array('eq',$ids[0]);
		    }
	    }	
	    if (!empty($tag['score'])) {
		    $score = explode(',',$tag['score']);
		    if (count($score) > 1) {
			    $where['user_score'] = array('between',$score[0].','.$score[1]);
		    }else{
			    $where['user_score'] = array('gt',$score[0]);
		    }
	    }			
	    if (!empty($tag['login'])) {
		    $login = explode(',',$tag['login']);
		    if (count($login) > 1) {
			    $where['user_login'] = array('between',$login[0].','.$login[1]);
		    }else{
			    $where['user_login'] = array('gt',$login[0]);
		    }
	    }		
        if(!empty($tag['addtime'])){
		    $time = explode(',',$tag['addtime']);
		    if(count($time) > 1) {
			    $where['user_reg_time'] = array('between',intval(strtotime($time[0])).','.intval(strtotime($time[1])));
		    }else{
			    $where['user_reg_time'] = array('gt',intval(strtotime($time[0])));
		    }			
        }	
        if(!empty($tag['page'])){
			if(config('route')){
				$route=config('route');
			}else{
				$route=$GLOBALS['route'];
			}
            $url=urldecode(zanpian_user_url($route,config('params')));
		    $data = db('user')->where($where)->field($tag['field'])->order($tag['order'])->paginate($tag['limit'],false,['path'=>$url]);
		}else{
			$limit_str = intval(abs($tag['start'])).",".intval(abs($tag['limit']));
			$data = db('user')->where($where)->order($tag['order'])->limit($limit_str)->select();
		}
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){
			cache::tag('foreach_user')->set($cahce['cache_name'],$data,intval($cahce['cache_time'])); 
	    }		
		return $data;
    }
	
		
}
// +----------------------------------------------------------------------
// | ZanPianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpiancms.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.zanpiancms.cc>
// +----------------------------------------------------------------------
?>